import { execFileSync } from 'child_process'
import { resolve } from 'path'
import { fileURLToPath, URL } from 'url'
import vueI18n from '@intlify/unplugin-vue-i18n/vite'
import vue from '@vitejs/plugin-vue'
import vueRouter from 'unplugin-vue-router/vite'
import { defineConfig, PluginOption } from 'vite'

const GIT_HEAD = execFileSync('git', ['rev-parse', 'HEAD']).toString().trim()

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    host: '127.0.0.1',
    port: 3000,
  },
  plugins: [
    vueRouter({
      routesFolder: [
        { src: resolve(__dirname, './src/pages') },
        {
          src: resolve(__dirname, './src/stories'),
          path: 'story/',
          extensions: ['.story.vue'],
        },
      ],
      extendRoute(route) {
        if (!route.name.startsWith('/story/')) {
          return
        }

        route.addToMeta({
          isStory: route.name !== '/story/',
          hasStoryNav: true,
        })
      },
    }),
    vue(),
    vueI18n({
      include: resolve(__dirname, '../web-core/lib/locales/**'),
    }),
  ] as PluginOption[],
  define: {
    XO_LITE_VERSION: JSON.stringify(process.env.npm_package_version),
    XO_LITE_GIT_HEAD: JSON.stringify(GIT_HEAD),
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      '@core': fileURLToPath(new URL('../web-core/lib', import.meta.url)),
    },
  },

  // https://vitejs.dev/guide/dep-pre-bundling.html#monorepos-and-linked-dependencies
  build: {
    rollupOptions: {
      output: {
        manualChunks: id => {
          if (id.includes('node_modules')) {
            if (id.includes('vue') || id.includes('pinia')) {
              return 'vue'
            }

            if (id.includes('lodash-es')) {
              return 'lodash-es'
            }

            if (id.includes('echarts')) {
              return 'charts'
            }
          }
        },
      },
      plugins: [
        {
          name: 'emit-build-json',
          generateBundle() {
            const content = {
              version: process.env.npm_package_version,
              gitHead: GIT_HEAD,
              date: new Date().toISOString(),
            }

            // Emit a virtual file directly into the bundle
            this.emitFile({
              type: 'asset',
              fileName: 'build.json',
              source: JSON.stringify(content, null, 2),
            })
          },
        },
      ],
    },
    commonjsOptions: {
      include: [/complex-matcher/, /node_modules/],
    },
    target: 'es2020',
  },
  optimizeDeps: {
    include: ['complex-matcher'],
    esbuildOptions: {
      target: 'es2020',
      tsconfigRaw: {
        // https://github.com/vitejs/vite/issues/15201#issuecomment-1875543124
        compilerOptions: {
          experimentalDecorators: true,
        },
      },
    },
  },
  esbuild: {
    tsconfigRaw: {
      // https://github.com/vitejs/vite/issues/15201#issuecomment-1875543124
      compilerOptions: {
        experimentalDecorators: true,
      },
    },
  },
})
